<template>
  <div class="container"  style="padding: 0px">
    <el-card class="box-card" style="height: inherit;padding-bottom: 20px">
      <div slot="header" class="clearfix">
        <span class="el-icon-document">待办任务</span>
        <el-tag style="margin-left:10px">发起人:{{ startUser }}</el-tag>
        <el-tag>任务节点:{{ taskName }}</el-tag>
        <el-button style="float: right;" size="mini" type="danger" @click="goBack">关闭</el-button>
      </div>
      <el-tabs tab-position="top" v-model="activeName" @tab-click="handleClick">
        <!--表单信息-->
        <el-tab-pane label="表单信息" name="1">
          <el-col :span="16" :offset="4">
            <div class="test-form">
              <!--              <parser :key="new Date().getTime()" :form-conf="variablesData"/>-->
              <!--              <parser :key="new Date().getTime()" :form-conf="variablesData" @submit="submitForm" ref="parser"/>-->
              <v-form-render :key="new Date().getTime()" ref="vFormRef" :form-json="variablesData" :form-data="formData"
                             :option-data="optionData">
              </v-form-render>
            </div>
            <div style="margin-left:15%;margin-bottom: 20px;font-size: 14px;">
              <el-button v-if="formKeyExist" icon="Check" type="success"
                         @click="handleComplete">审批
              </el-button>
              <el-button icon="Check" type="primary" @click="handleDelegate">委派</el-button>
              <el-button icon="Check" type="primary" @click="handleAssign">转办</el-button>
              <el-button icon="Check" type="primary" @click="handleDelegate">签收</el-button>
              <el-button icon="CaretLeft" type="warning" @click="handleReturn">退回</el-button>
              <el-button icon="Close" type="danger" @click="handleReject">驳回</el-button>
            </div>
          </el-col>
        </el-tab-pane>
        <!--流程流转记录-->
        <el-tab-pane label="流转记录" name="2">
          <!--flowRecordList-->
          <el-col :span="16" :offset="4">
            <div class="block">
              <el-timeline>
                <el-timeline-item
                    v-for="(item,index ) in flowRecordList"
                    :key="index"
                    :icon="setIcon(item.finishTime)"
                    :color="setColor(item.finishTime)"
                >
                  <p style="font-weight: 700">{{ item.taskName }}</p>
                  <el-card :body-style="{ padding: '10px' }">
                    <el-descriptions class="margin-top" :column="1" size="small" border>
                      <el-descriptions-item v-if="item.assigneeName" label-class-name="my-label">
                        <template #label>
                          <div class="cell-item">
                            <el-icon>
                              <UserFilled></UserFilled>
                            </el-icon>
                            办理人
                          </div>
                        </template>
                        {{ item.assigneeName }}
                        <el-tag type="info" size="mini">{{ item.deptName }}</el-tag>
                      </el-descriptions-item>
                      <el-descriptions-item v-if="item.candidate" label-class-name="my-label">
                        <template #label>
                          <div class="cell-item">
                            <el-icon>
                              <UserFilled></UserFilled>
                            </el-icon>
                            候选办理
                          </div>
                        </template>
                        {{ item.candidate }}
                      </el-descriptions-item>
                      <el-descriptions-item label-class-name="my-label">
                        <template #label>
                          <div class="cell-item">
                            <el-icon>
                              <Stopwatch/>
                            </el-icon>
                            接收时间
                          </div>
                        </template>
                        {{ item.createTime }}
                      </el-descriptions-item>
                      <el-descriptions-item v-if="item.finishTime" label-class-name="my-label">
                        <template #label>
                          <div class="cell-item">
                            <el-icon>
                              <Stopwatch/>
                            </el-icon>
                            处理时间
                          </div>
                        </template>
                        {{ item.finishTime }}
                      </el-descriptions-item>
                      <el-descriptions-item v-if="item.duration" label-class-name="my-label">
                        <template #label>
                          <div class="cell-item">
                            <el-icon>
                              <Timer/>
                            </el-icon>
                            耗时
                          </div>
                        </template>
                        {{ item.duration }}
                      </el-descriptions-item>
                      <el-descriptions-item v-if="item.comment" label-class-name="my-label">
                        <template #label>
                          <div class="cell-item">
                            <el-icon>
                              <Tickets/>
                            </el-icon>
                            >处理意见
                          </div>
                        </template>
                        {{ item.comment.comment }}
                      </el-descriptions-item>
                    </el-descriptions>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-col>
        </el-tab-pane>
        <!--流程图-->
        <el-tab-pane label="流程图" name="3">
          <flow :flowData="flowData"/>
        </el-tab-pane>
      </el-tabs>
      <!--审批任务-->
      <el-dialog :title="completeTitle" v-model="completeOpen" width="60%" append-to-body>
        <el-form ref="submittaskForm" :model="taskForm">
          <el-form-item prop="targetKey">
            <flow-user v-if="checkSendUser" :checkType="checkType" @handleUserSelect="handleUserSelect"></flow-user>
            <flow-role v-if="checkSendRole" @handleRoleSelect="handleRoleSelect"></flow-role>
          </el-form-item>
          <el-form-item label="处理意见" label-width="80px" prop="comment"
                        :rules="[{ required: true, message: '请输入处理意见', trigger: 'blur' }]">
            <el-input type="textarea" v-model="taskForm.comment" placeholder="请输入处理意见"/>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="completeOpen = false">取 消</el-button>
          <el-button type="primary" @click="taskComplete">确 定</el-button>
        </span>
      </el-dialog>
      <!--退回流程-->
      <el-dialog :title="returnTitle" v-model="returnOpen" width="40%" append-to-body>
        <el-form ref="submittaskForm" :model="taskForm" label-width="80px">
          <el-form-item label="退回节点" prop="targetKey">
            <el-radio-group v-model="taskForm.targetKey">
              <el-radio-button
                  v-for="item in returnTaskList"
                  :key="item.id"
                  :label="item.id"
              >{{ item.name }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="退回意见" prop="comment"
                        :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]">
            <el-input style="width: 50%" type="textarea" v-model="taskForm.comment" placeholder="请输入意见"/>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
              <el-button @click="returnOpen = false">取 消</el-button>
              <el-button type="primary" @click="taskReturn(submittaskForm)">确 定</el-button>
          </span>
      </el-dialog>
      <!--驳回流程-->
      <el-dialog :title="rejectTitle" v-model="rejectOpen" width="40%" append-to-body>
        <el-form ref="submittaskForm" :model="taskForm" label-width="80px">
          <el-form-item label="驳回意见" prop="comment"
                        :rules="[{ required: true, message: '请输入意见', trigger: 'blur' }]">
            <el-input style="width: 50%" type="textarea" v-model="taskForm['comment']" placeholder="请输入意见"/>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="rejectOpen = false">取 消</el-button>
            <el-button type="primary" @click="taskReject(submittaskForm)">确 定</el-button>
          </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import FlowUser from '@/components/flow/User/index.vue'
import FlowRole from '@/components/flow/Role/index.vue'
import flow from '@/views/admin/task/todoprocessdeatil/flow.vue'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {fetchData, saveorUpadateDate} from "@/api/index";
import {ref, reactive, onMounted,watch} from "vue";
import {useRoute, useRouter} from "vue-router";
import {ElMessage} from "element-plus";
import {useStore} from "vuex";

let route = useRoute()
let router = useRouter()
let store = useStore()
let vFormRef = ref(null)
let xmlData = ref("")
let flowData = ref([])
let optionData = reactive({})
let formData = ref({})
let activeName = ref("1")
let deptName = ref(undefined)
let userList = ref(null)
let defaultProps = reactive({
  children: "children",
  label: "label"
})
let queryParams = reactive({
  deptId: undefined
})
let loading = ref(true)
let flowRecordList = ref([])
let formConfCopy = reactive({})
let src = ref(null)
let rules = reactive({})
let variablesForm = reactive({})
let taskForm = reactive({
      returnTaskShow: false, // 是否展示回退表单
      delegateTaskShow: false, // 是否展示回退表单
      defaultTaskShow: true, // 默认处理
      comment: "", // 意见内容
      procInsId: "", // 流程实例编号
      instanceId: "", // 流程实例编号
      deployId: "",  // 流程定义编号
      taskId: "",// 流程任务编号
      procDefId: "",  // 流程编号
      targetKey: "",
      variables: {
        variables: {}
      },
    }
)
let assignee = ref(null)
let formConf = reactive({})
let variables = ref([])
let variablesData = ref({})
let returnTaskList = ref([])
let completeTitle = ref(null)
let completeOpen = ref(false)
let returnTitle = ref(null)
let returnOpen = ref(null)
let rejectOpen = ref(null)
let rejectTitle = ref(null)
let userData = ref(null)
let checkSendUser = ref(false)
let checkSendRole = ref(false)
let checkType = ref("single")
let taskName = ref(null)
let startUser = ref(null)
let multiInstanceVars = ref("")
let formKeyExist = ref(false)
let submittaskForm = ref(null)

onMounted(() => {
 load()
})
const load = () => {
  if (route.query) {
    taskName.value = route.query.taskName;
    startUser.value = route.query.startUser;
    taskForm.deployId = route.query.deployId;
    taskForm.taskId = route.query.taskId;
    taskForm.procInsId = route.query.procInsId;
    taskForm.executionId = route.query.executionId;
    taskForm.instanceId = route.query.procInsId;
    // 流程任务获取变量信息
    if (taskForm.taskId) {
      // this.processVariables(this.taskForm.taskId)
      getFlowTaskForm(taskForm.taskId)
    }
    getFlowRecordList(taskForm.procInsId, taskForm.deployId);
  }
}
const getFlowTaskForm = (taskId: any) => {
  if (taskId) {
    // 提交流程申请时填写的表单存入了流程变量中后续任务处理时需要展示
    fetchData("/process/flowable/task/flowTaskForm", {taskId: taskId}).then(res => {
      variablesData.value = res.formJson;
      taskForm.variables = res;
      formData.value = res.formData;
      formKeyExist.value = res.formKeyExist;
    });
  }
}
const handleClick = (tab: any, event: any) => {
  if (tab.paneName === '3') {
    fetchData("/process/flowable/task/flowXmlAndNode/", {
      procInsId: taskForm.procInsId,
      deployId: taskForm.deployId
    }).then(res => {
      flowData.value = res;
    })
  }
}

const setIcon = (val: any) => {
  if (val) {
    return "el-icon-check";
  } else {
    return "el-icon-time";
  }
}
const setColor = (val: any) => {
  if (val) {
    return "#2bc418";
  } else {
    return "#b3bdbb";
  }
}
const getFlowRecordList = (procInsId: any, deployId: any) => {
  const params = {procInsId: procInsId, deployId: deployId}
  fetchData("/process/flowable/task/flowRecord", params).then(res => {
    flowRecordList.value = res.flowList;
  }).catch(res => {
    goBack();
  })
}
const fillFormData = (form: any, data: any) => {
  form.fields.forEach(item => {
    const val = data[item.__vModel__]
    if (val) {
      item.__config__.defaultValue = val
    }
  })
}

/** 加载审批任务弹框 */
const handleComplete = () => {
  // this.completeOpen = true;
  // this.completeTitle = "流程审批";
  submitForm(null);
}

/** 用户审批任务 */
const taskComplete = () => {
  vFormRef.value.getFormData().then(submitdata => {
    taskForm.variables = submitdata;
    if (!taskForm.variables && checkSendUser.value) {
      ElMessage.error("请选择流程接收人员!");
      return;
    }
    if (!taskForm.variables && checkSendRole.value) {
      ElMessage.error("请选择流程接收角色组!");
      return;
    }
    if (!taskForm.comment) {
      ElMessage.error("请输入审批意见!");
      return;
    }
    vFormRef.value.disableForm()
    taskForm.variables["formJson"] = variablesData
    if (taskForm && formKeyExist.value) {
      saveorUpadateDate("/process/flowable/task/complete", taskForm).then(response => {
        // this.$modal.msgSuccess(response.msg);
        completeOpen.value=false
        goBack();
      });
    } else {
      // 流程设计人员类型配置为固定人员接收任务时,直接提交任务到下一步
      saveorUpadateDate("/process/flowable/task/complete", taskForm).then(response => {
        // this.$modal.msgSuccess(response.msg);
        completeOpen.value=false
        goBack();
      });
    }
  })
}
/** 委派任务 */
const handleDelegate = () => {
  taskForm.delegateTaskShow = true;
  taskForm.defaultTaskShow = false;
}
const handleAssign = () => {

}
const goBack = () => {
  // 关闭当前标签页并返回上个页面
  store.dispatch('tagsView/delRouterView', {
    "path":"/admin/task/todoprocess",
  })
  router.push("/admin/task/todoprocess")
}

/** 驳回任务 */
const handleReject = () => {
  rejectOpen.value = true;
  rejectTitle.value = "驳回流程";
}
/** 驳回任务 */
const taskReject = (form) => {
  debugger
  form.validate(valid => {
    if (valid) {
      saveorUpadateDate("/process/flowable/task/reject", taskForm).then(res => {
        // this.$modal.msgSuccess(res.msg);
        goBack();
      });
    }
  });
}

/** 可退回任务列表 */
const handleReturn = () => {
  returnOpen.value = true;
  returnTitle.value = "退回流程";
  saveorUpadateDate("/process/flowable/task/returnList", taskForm).then((res: any) => {
    returnTaskList.value = res;
    taskForm.variables = null;
  })
}
/** 提交退回任务 */
const taskReturn = (form) => {
  form.validate(valid => {
    if (valid) {
      saveorUpadateDate("/process/flowable/task/return", taskForm).then(res => {
        // this.$modal.msgSuccess(res.msg);
        goBack()
      });
    }
  })
}
/** 取消回退任务按钮 */
const cancelTask = () => {
  taskForm.returnTaskShow = false;
  taskForm.defaultTaskShow = true;
  returnTaskList.value = [];
}
/** 委派任务 */
const submitDeleteTask = () => {
  submittaskForm.validate(valid => {
    if (valid) {
      saveorUpadateDate("/process/flowable/task/delegate", taskForm).then(response => {
        // this.$modal.msgSuccess(response.msg);
        goBack();
      });
    }
  });
}
/** 取消回退任务按钮 */
const cancelDelegateTask = () => {
  taskForm.delegateTaskShow = false;
  taskForm.defaultTaskShow = true;
  returnTaskList.value = [];
}
/** 申请流程表单数据提交 */
const submitForm = (formData) => {
  // 根据当前任务或者流程设计配置的下一步节点 todo 暂时未涉及到考虑网关、表达式和多节点情况
  const params = {taskId: taskForm.taskId}
  saveorUpadateDate("/process/flowable/task/nextFlowNode", params).then(res => {
    const data = res;
    taskForm.formData = formData;
    if (data) {
      if (data.dataType === 'dynamic') {
        if (data.type === 'assignee') { // 指定人员
          checkSendUser.value = true;
          checkType.value = "single";
        } else if (data.type === 'candidateUsers') {  // 候选人员(多个)
          checkSendUser.value = true;
          checkType.value = "multiple";
        } else if (data.type === 'candidateGroups') { // 指定组(所属角色接收任务)
          checkSendRole.value = true;
        } else { // 会签
          // 流程设计指定的 elementVariable 作为会签人员列表
          multiInstanceVars.value = data.vars;
          checkSendUser.value = true;
          checkType.value = "multiple";
        }
      }
    }
    completeOpen.value = true;
    completeTitle.value = "流程审批";
  })
}

</script>
<style lang="scss" scoped>
.test-form {
  margin: 15px auto;
  width: 800px;
  padding: 15px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
</style>